package com.jy.datapipeline.common.util;

import cn.hutool.core.collection.ListUtil;
import com.alibaba.fastjson.JSONObject;
import com.jy.datapipeline.common.constants.ExpConstants;
import com.jy.datapipeline.common.exception.GlobalException;
import com.jy.datapipeline.importserver.common.dto.ImportDataSourceNamesDto;

import java.util.*;

/**
 * @类名 ConvertUtil
 * @描述 TODO
 * @作者 白条君
 * @创建日期 2023/4/17 12:34
 * @版本 1.0
 */
public class ConvertUtil{

    public static Map<String, Object> convertMap(Object object) {
        Map<String, Object> map = new HashMap<>();
        Map jsonMap = JSONObject.parseObject(JSONObject.toJSONString(object), Map.class);
        for (Object obj : jsonMap.entrySet()) {
            Object key = ((Map.Entry<?, ?>) obj).getKey();
            Object value = ((Map.Entry<?, ?>) obj).getValue();
            map.put((String) key, value);
        }
        return map;
    }

    public static <T> List<T> convertArray(Object obj, Class<T> clazz) {
        List<T> result = new ArrayList<>();
        if (obj instanceof List<?>) {
            for (Object o : (List<?>) obj) {
                result.add(clazz.cast(o));
            }
            return result;
        }
        return ListUtil.empty();
    }

    public static <T> T convertObject(Object obj, Class<T> clazz) {
        if (obj.getClass().equals(clazz)) {
            return clazz.cast(obj);
        }
        throw new GlobalException(ExpConstants.TYPE_CONVERT_EXP);
    }
}
